<template>
  <div class="bill-management">
  <div class="page-header">
    <h2>订单管理</h2>
  </div>

  <!-- 搜索区域 -->
  <div class="search-area">
    <el-form :model="searchForm" inline>
      <el-form-item label="订单信息">
        <el-input v-model="searchForm.billInfo" placeholder="请输入订单信息" clearable />
      </el-form-item>
      <el-form-item label="用户信息">
        <el-input v-model="searchForm.userInfo" placeholder="请输入用户信息" clearable />
      </el-form-item>
      <el-form-item label="订单来源">
        <el-select v-model="searchForm.billForm" placeholder="请选择订单来源" clearable>
          <el-option label="微信" :value="1" />
          <el-option label="支付宝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="发货方式">
        <el-select v-model="searchForm.billWay" placeholder="请选择发货方式" clearable>
          <el-option label="自提" :value="1" />
          <el-option label="配送" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="searchForm.billState" placeholder="请选择状态" clearable>
          <el-option label="未完成" :value="1" />
          <el-option label="完成" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchBills">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          新增订单
        </el-button>
      </el-form-item>
    </el-form>
  </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="billList" v-loading="loading" stripe>
        <el-table-column prop="billId" label="订单ID" width="80" />
        <el-table-column prop="billInfo" label="订单信息" width="200" />
        <el-table-column prop="userInfo" label="用户信息" width="200" />
        <el-table-column prop="billForm" label="订单来源" width="120">
          <template #default="{ row }">
            {{ getBillFormText(row.billForm) }}
          </template>
        </el-table-column>
        <el-table-column prop="billWay" label="发货方式" width="120">
          <template #default="{ row }">
            {{ getBillWayText(row.billWay) }}
          </template>
        </el-table-column>
        <el-table-column prop="billState" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.billState)">
              {{ getStatusText(row.billState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editBill(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteBill(row.billId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑订单' : '新增订单'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="billForm" :rules="billRules" ref="billFormRef" label-width="100px">
        <el-form-item label="订单信息" prop="billInfo">
          <el-input v-model="billForm.billInfo" placeholder="请输入订单信息" />
        </el-form-item>
        <el-form-item label="用户信息" prop="userInfo">
          <el-input v-model="billForm.userInfo" placeholder="请输入用户信息" />
        </el-form-item>
        <el-form-item label="订单来源" prop="billForm">
          <el-select v-model="billForm.billForm" placeholder="请选择订单来源">
            <el-option label="微信" :value="1" />
            <el-option label="支付宝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="发货方式" prop="billWay">
          <el-select v-model="billForm.billWay" placeholder="请选择发货方式">
            <el-option label="自提" :value="1" />
            <el-option label="配送" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="billState">
          <el-select v-model="billForm.billState" placeholder="请选择状态">
            <el-option label="未完成" :value="1" />
            <el-option label="完成" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { billApi } from '@/api/bill'

// 响应式数据
const loading = ref(false)
const billList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const billFormRef = ref()

// 搜索表单
const searchForm = reactive({
  billInfo: '',
  userInfo: '',
  billForm: null,
  billWay: null,
  billState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 订单表单
const billForm = reactive({
  billId: null,
  billInfo: '',
  userInfo: '',
  billForm: null,
  billWay: null,
  billState: null
})

// 表单验证规则
const billRules = {
  billInfo: [
    { required: true, message: '请输入订单信息', trigger: 'blur' }
  ],
  userInfo: [
    { required: true, message: '请输入用户信息', trigger: 'blur' }
  ],
  billForm: [
    { required: true, message: '请选择订单形式', trigger: 'change' }
  ],
  billWay: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  billState: [
    { required: true, message: '请选择订单状态', trigger: 'change' }
  ]
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'warning',
    2: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '未完成',
    2: '完成'
  }
  return statusMap[status] || '未知'
}

// 获取订单来源文本
const getBillFormText = (form) => {
  const formMap = {
    1: '微信',
    2: '支付宝'
  }
  return formMap[form] || '未知'
}

// 获取发货方式文本
const getBillWayText = (way) => {
  const wayMap = {
    1: '自提',
    2: '配送'
  }
  return wayMap[way] || '未知'
}

// 搜索订单
const searchBills = async () => {
  loading.value = true
  try {
    const response = await billApi.getBillList(searchForm)
    if (response.code === 200) {
      billList.value = response.data || []
      pagination.total = billList.value.length
    }
  } catch (error) {
    console.error('搜索订单失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    billInfo: '',
    userInfo: '',
    billState: null
  })
  searchBills()
}

// 编辑订单
const editBill = (row) => {
  isEdit.value = true
  Object.assign(billForm, row)
  showAddDialog.value = true
}

// 删除订单
const deleteBill = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await billApi.deleteBill(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchBills()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await billFormRef.value.validate()
    
    const response = isEdit.value 
      ? await billApi.updateBill(billForm)
      : await billApi.addBill(billForm)
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchBills()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(billForm, {
    billId: null,
    billInfo: '',
    userInfo: '',
    billForm: null,
    billWay: null,
    billState: null
  })
  isEdit.value = false
  billFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchBills()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchBills()
}

// 初始化
onMounted(() => {
  searchBills()
})
</script>

<style scoped>
.bill-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>